package util

import (
	"encoding/json"
	"fmt"
	"os"

	"gitee.com/eliminate/domain"
)

type MonsterConfig struct {
	ID string `json:"id"`
}
type GridConfig struct {
	ID   int   `json:"id"`
	Row  int   `json:"row"`
	Col  int   `json:"col"`
	Data []int `json:"data"`
}

func (g GridConfig) toString() {
	fmt.Println("\nid: ", g.ID)

	for i := 0; i < g.Row; i++ {
		for j := 0; j < g.Col; j++ {
			fmt.Print(g.Data[i*g.Col+j], " ")
		}
		fmt.Println()
	}
}

type GenerateGrid struct {
	GridConfigs    []GridConfig
	MonsterConfigs []MonsterConfig
	Grid           []domain.Cell
}

func decoder(file string, any interface{}) interface{} {
	fp, _ := os.Open(file)
	dec := json.NewDecoder(fp)
	for {
		err := dec.Decode(&any)
		if err != nil {
			// fmt.Println("error", err)
			break
		}
	}
	return any
}

func (grid *GenerateGrid) readGridConfig() {
	var datas []GridConfig
	fp, _ := os.Open("grid.json")
	dec := json.NewDecoder(fp)
	for {
		err := dec.Decode(&datas)
		if err != nil {
			// fmt.Println("error", err)
			break
		}
	}

	for _, line := range datas {
		if line.Col*line.Row > len(line.Data) {
			fmt.Println("data field is invalid, grid id =", line.ID)
			os.Exit(1)
		}
	}
	grid.GridConfigs = datas
}

func (grid *GenerateGrid) readMonsterConfig() {
	var datas []MonsterConfig
	datas = decoder("monster.json", datas).([]MonsterConfig)

	grid.MonsterConfigs = datas
}

// func (grid *GenerateGrid) readMonsterConfig() {
// 	var datas []MonsterConfig
// 	fp, _ := os.Open("monster.json")
// 	dec := json.NewDecoder(fp)
// 	for {
// 		err := dec.Decode(&datas)
// 		if err != nil {
// 			// fmt.Println("error", err)
// 			break
// 		}
// 	}

// 	grid.MonsterConfigs = datas
// }

func (grid *GenerateGrid) createGrid(id int) {
	grid.readGridConfig()
	grid.readMonsterConfig()

	for _, cell := range grid.GridConfigs[id].Data {
		if cell == domain.StoneType {
			continue
		}
	}
}
